<?php

declare(strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use app\common\tool\Result;
use app\common\model\User;
use app\common\model\Level;
use app\common\model\PreceptEvaluate;
use think\facade\View;
use think\Response;
use think\exception\ValidateException;
use think\response\Json;
//该文件为自动生成，请按需修改
class Precept extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Precept';

    protected $hasOne = ['user', 'admin', 'huser', 'tuser'];

    protected $append = ['statusText', 'typeText'];
    
    protected int $takeOver = 3;

    public function index(): string
    {
        $param = $this->request->param();
        if ($this->admin->id != 1) {
            $extra_map[] = ['admin_id', '=', $this->admin->id];
        }
        $rb = [];
        if (isset($param['status'])) {
            $extra_map[] = ['status', '=', $param['status']];
            if ($param['status'] == 1) {
                $rb = [
                    'allot' => [
                        'title'       => '分配专家',
                        'unity_title' => '专家/服务团队',
                        'url'   => url('precept/preceptAllot')->build(),
                        'w' => '40%',
                        'h' => '60%',
                        'event' => 'audit'
                    ]
                ];
            } else if ($param['status'] == 3) {
                $rb = [
                    'allot' => [
                        'title'       => '报价处理',
                        'unity_title' => '方案报价处理',
                        'url'   => url('precept/preceptOffer')->build(),
                        'w' => '50%',
                        'h' => '90%',
                        'event' => 'audit'
                    ]
                ];
            } else if ($param['status'] == 6) {
                $rb = [
                    'allot' => [
                        'title'       => '查看评价',
                        'unity_title' => '方案评价信息',
                        'url'   => url('precept/evaluate')->build(),
                        'w' => '40%',
                        'h' => '80%',
                        'event' => 'audit'
                    ]
                ];
            }
        } else {
            $extra_map[] = ['status', '>', 0];
        }
        return Builder::Table()
            ->addColumn(['type' => 'checkbox', 'fixed' => 'left', 'title' => '全选'])
            ->addColumn(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addColumn(['field' => 'sn', 'title' => '方案编号'])
            ->addColumn(['field' => 'rname', 'title' => '姓名'])
            ->addColumn(['field' => 'tel', 'title' => '电话'])
            ->addColumn(['field' => 'typeText', 'title' => '需求类型'])
            ->addColumn(['field' => 'content', 'title' => '需求内容', 'templet' => '#editorTpl'])
            ->addColumn(['field' => 'images', 'title' => '需求图片', 'templet' => '#imagesTpl'])
            ->addColumn(['field' => 'note', 'title' => '需求备注', 'templet' => '#noteTpl'])
            ->addColumn(['field' => 'code', 'title' => '方案用户', 'templet' => '#_userTpl'])
            ->addColumn(['field' => 'acode', 'title' => '运营经理', 'templet' => '#_adminTpl'])
            ->addColumn(['field' => 'hcode', 'title' => '健康师', 'templet' => '#_huserTpl'])
            ->addColumn(['field' => 'tcode', 'title' => '专家/服务团队', 'templet' => '#_tuserTpl'])
            ->addColumn(['field' => 'statusText', 'title' => '状态'])
            ->addColumn(['field' => 'create_time', 'title' => '创建时间'])
            ->addColumn(['field' => 'update_time', 'title' => '更新时间'])
            ->addColumn(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 260])
            ->addTabList([
                'filed' => 'status',
                'list' => $this->model::getStatusList($this->admin->id),
                'url' => url('index')
            ])
            ->addSearch([
                ['uid', '用户编号/昵称/手机号', 'input', '', '\app\common\model\User', 'code|nickname|mobile,id'],
                ['sn', '方案编号', 'input,Like'],
                ['rname', '姓名', 'input,Like'],
                ['tel', '电话', 'input,Like'],
            ])
            ->addTopButtons(['dropdown' => [
                'title' => '导出数据',
                'icon' => 'layui-icon-upload-drag',
                'class' => 'normal import-boost Dropdown',
                'layon' => '.Dropdown',
                'event' => '_dropdownExcel',
                'init' => true
            ]])
            ->addRightButtons(array_merge($rb, [
                'edit_show' => [
                    'title'       => '查看详情',
                    'unity_title' => '方案详情信息',
                    'url'   => url('precept/info')->build(),
                    'w' => '80%',
                    'h' => '90%',
                    'event' => 'audit'
                ],
                'delete'
            ]))
            ->addExtraMap($extra_map)
            ->fetch();
    }

    /**
     * 获取相关会员列表
     */
    public  function getUserList()
    {
        try {
            $param = $this->request->param();
            $list = User::where('level_id','>', 2)
                ->field('id,code,mobile,nickname,level_id')->where('is_lock',0)->whereLike('code|mobile|nickname', '%' . $param['val'] . '%')->page(intval($param['page'] ?? 1), intval($param['limit'] ?? 10))->select();
            foreach($list as &$v){
                $v->level_title = Level::where('id',$v->level_id)->value('title');
            }
            $count = User::where('level_id','>', 2)->where('is_lock',0)->whereLike('code|mobile|nickname', '%' . $param['val'] . '%')->count();
            return Result::fastReturn(['code' => 0, 'data' => $list, 'count' => $count]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取团队信息
     */
    public  function getTeamUserList()
    {
        try {
            $param = $this->request->param();
            $list = User::where('level_id','>', 2)
                ->field('id,code,mobile,nickname,level_id')->where('is_lock',0)->page(intval($param['page'] ?? 1), intval($param['limit'] ?? 10))->select();
            foreach($list as &$v){
                $v->level_title = Level::where('id',$v->level_id)->value('title');
            }
            $count = User::where('level_id','>', 2)->where('is_lock',0)->count();
            return Result::fastReturn(['code' => 0, 'data' => $list, 'count' => $count]);
        } catch (\Exception $e){}
    }
    /**
     * 获取用户信息
     */
    public  function getUserInfo()
    {
        try {
            $param = $this->request->param();
            $user = User::where('id', $param['uid'])->field('id,code,mobile,nickname')->find();
            return Result::success('success', $user, 0);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 选择专家
     */
    public function preceptAllot($id = '')
    {

        if ($this->request->isPost()) {
            $param = $this->request->param();
            try {
                return Result::fastReturn($this->model::preceptAllot($param, $this->admin));
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
        }
        $info = $this->model::find($id);
        View::assign([
            'info'    => $info,
        ]);
        return View::fetch('precept/allot');
    }
    /**
     * 报价处理
     */
    public function preceptOffer($id = '')
    {

        if ($this->request->isPost()) {
            $param = $this->request->param();
            try {
                return Result::fastReturn($this->model::preceptOffer($param, $this->admin));
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
        }
        $info = $this->model::find($id);
        View::assign([
            'info'    => $info,
        ]);
        return View::fetch('precept/offer');
    }
    /**
     * 查看详情
     */
     public function info($id = '')
     {
         $info = $this->model::find($id);
         View::assign([
             'info'    => $info,
         ]);
         return View::fetch('precept/info');
     }
    /**
     * 评价
     */
    public function evaluate($id = '')
    {
        $info = PreceptEvaluate::where(['precept_id' => $id])->find();
        $list = PreceptEvaluate::getComment();
        foreach ($list as &$v) {
            foreach ($v['son'] as &$vv) {
                if (!empty($info)) {
                    if ($vv['score'] == $info['score_' . $v['id']]) {
                        $vv['check'] = true;
                    } else {
                        $vv['check'] = -1;
                    }
                } else {
                    $vv['check'] = -1;
                }
            }
        }
        View::assign([
            'info'    => $info,
            'list' => $list
        ]);
        return View::fetch();
    }
}
